<template>
    <div class="MyAudio">
        <audio ref="player" :muted="true" :src="audioSrc" @canplay="handleCanPlay" controls autoplay></audio>
    </div>
</template>
  
<script lang="ts">
import kekeAudio from '@/assets/mp/keke.mp3'

export default defineComponent({
    name: 'AudioPlayer',
    props: {
        audioUrl: {
            type: String,
            default: kekeAudio
        },
        timeNum: {
            type: Number,
            default: 800
        },
    },
    emits: ['endPlay'], // 定义要发出的自定义事件
    setup(props) {
        const instance = getCurrentInstance(); // 获取当前组件实例
        const player = ref();
        let audioSrc = ref('');
        // 当组件挂载时设置音频源
        onMounted(() => {
            audioSrc.value = props.audioUrl;
        });

        // 处理 canplay 事件
        const handleCanPlay = () => {
            // 在这里可以添加额外处理逻辑，但上面的 watch 已经尝试播放音频了
            if (player.value) {
                player.value.muted = false
                player.value.play();
                setTimeout(() => {
                    instance?.emit('endPlay')
                    player.value.muted = true
                }, props.timeNum);
            }
        };

        return {
            player,
            audioSrc,
            handleCanPlay,
        };
    }
})
</script>

<style lang="scss" scoped>
.MyAudio {
    display: none;
}
</style>